<template>
  <div class="account-box">
    <div class="toggle">
      <a
        href="javascript:;"
        v-if="activeForm === 'accountForm'"
        @click="activeForm = 'messageForm'"
      >
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
      <a
        href="javascript:;"
        v-if="activeForm === 'messageForm'"
        @click="activeForm = 'accountForm'"
      >
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
    </div>
    <Form ref="formCom" class="form" v-slot="{ errors }" :validation-schema="schema">
      <!-- <h3>错误对象：{{ errors }}</h3> -->
      <!-- 使用账号登录的表单 -->
      <template v-if="activeForm === 'accountForm'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field
              :class="{ error: errors.account }"
              name="account"
              v-model="form.account"
              type="text"
              placeholder="请输入用户名或手机号"
            />
          </div>
          <div v-if="errors.account" class="error">
            <i class="iconfont icon-warning" />{{ errors.account }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field
              :class="{ error: errors.password }"
              name="password"
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
            />
          </div>
          <div v-if="errors.password" class="error">
            <i class="iconfont icon-warning" />{{ errors.password }}
          </div>
        </div>
      </template>
      <!-- 使用短信登录的表单 -->
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field
              :class="{ error: errors.mobile }"
              name="mobile"
              v-model="form.mobile"
              type="text"
              placeholder="请输入手机号"
            />
          </div>
          <div v-if="errors.mobile" class="error">
            <i class="iconfont icon-warning" />{{ errors.mobile }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field
              :class="{ error: errors.code }"
              name="code"
              v-model="form.code"
              type="text"
              placeholder="请输入验证码"
            />
            <span class="code" @click="sendCodeBtn()">{{number===0?'发送验证码':`${number}秒后发送`}}</span>
          </div>
          <div v-if="errors.code" class="error">
            <i class="iconfont icon-warning" />{{ errors.code }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <!-- <XtxCheckbox /> -->
          <!-- 💥 Field 可以通过 as 属性指定渲染成其他标签或者自定义组件，as 默认值为 input -->
          <Field as="XtxCheckbox" v-model="form.isAgree" name="isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div v-if="errors.isAgree" class="error">
          <i class="iconfont icon-warning" />{{ errors.isAgree }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="loginBtn">登录</a>
    </Form>
    <div class="action">
     <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
            <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
          </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { userAccountLogin, userMobileLoginMsg } from '@/api/user'
// import store from '@/store'
// import router from '@/router'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/shared'

export default {
  name: 'LoginForm',
  components: { Form, Field },
  setup () {
    const activeForm = ref('accountForm')
    // 用于手机表单数据的响应式对象
    const form = reactive({
      account: null,
      password: null,
      mobile: null,
      code: null,
      isAgree: true
    })

    const formCom = ref(null)
    const store = useStore()
    // router 路由器（管理路由的-老大）
    const router = useRouter()
    // route 路由 (小弟)
    // const route = useRoute()

    const loginBtn = async () => {
      // 主动获取表单校验结果
      const valid = await formCom.value.validate()
      // 手机号码+验证码登录
      if (!valid) return alert('表单校验失败')
      // console.log('表单校验是否通过', valid)
      // 测试账号：sujiehao   密码：123456
      try {
        const { result } = await userAccountLogin(form)
        // console.log(result)
        // 1. 存储 token 信息
        store.commit('user/setUser', result)
        // 2. 页面跳转（两种情况：1.回跳到某个页面 2.跳转首页）
        // router.currentRoute.value 获取当前路由
        const redirectUrl = router.currentRoute.value.query.redirectUrl
        router.push(redirectUrl || '/')
        Message({ type: 'success', message: '登录成功' })
        store.dispatch('cart/mergeLocalCart')
      } catch (err) {
        // 找到message的错误的
        // console.dir(err)
        Message({ type: 'error', message: err.response.data.message })
        // alert(err.response.data.message)
      }
    }
    // 定义一个变量初始值为0
    const number = ref(0)
    // 倒计时方法 vueuse里面的方法 resume为开始 pause为停止
    const { resume, pause } = useIntervalFn(() => {
      number.value--
      if (number.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })
    const sendCodeBtn = async () => {
      const mobileChecked = schema.mobile(form.mobile)
      console.log(111)
      if (mobileChecked === true) {
        // 上一个倒计时没结束，直接退出
        if (number.value !== 0) return
        // 点击了刚开始为60秒
        number.value = 60
        // 开始倒计时
        resume()
        // 调用接口
        try {
          await userMobileLoginMsg(form.mobile)
          Message({ type: 'success', message: '发送成功' })
        } catch (err) {
          Message({ type: 'error', message: '验证码已发送，等一会在试' })
        }
      } else {
        // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
        formCom.value.setFieldError('mobile', mobileChecked)
      }
    }
    return { activeForm, schema, form, formCom, loginBtn, sendCodeBtn, number }
  }
}
</script>

<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,&:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
